import React from 'react';
import { Route, Redirect, Switch } from 'react-router-dom';
import routesConfig, { IFMenuBase, IFMenu } from './config';
import AllComponents from '../components';
import RouteWrapper from './RouteWrapper';

const CustomRouters = () => {
  const createMenu = (r: IFMenu) => {
    const route = (r: IFMenuBase) => {
      const Component = r.component && AllComponents[r.component];
      return (
        <Route
          key={r.route || r.key}
          exact
          path={r.route || r.key}
          render={(props: any) => {
            // 重新包装组件
            const wrapper = (
              <RouteWrapper {...{ ...props, Comp: Component, route: r }} />
            );
            // return r.login ? wrapper : requireLogin(wrapper, r.requireAuth);
            return wrapper;
          }}
        />
      );
    };

    const subRoute = (r: IFMenu): any =>
      r.subs &&
      r.subs.map((subR: IFMenu) => (subR.subs ? subRoute(subR) : route(subR)));

    return r.component ? route(r) : subRoute(r);
  };

  const createRoute = (key: string) => routesConfig[key].map(createMenu);
  return (
    <Switch>
      {Object.keys(routesConfig).map((key) => createRoute(key))}
      <Route render={() => <Redirect to="/404" />}></Route>
    </Switch>
  );
};

export default CustomRouters;
